package com.huawei.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huawei.common.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义失败处理器
 */
@Component
public class AppLoginFailHandler implements AuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        // 处理post请求中文乱码问题
        // 设置请求字符编码为UTF-8
        request.setCharacterEncoding("UTF-8");
        // 设置响应字符编码为UTF-8
        response.setCharacterEncoding("UTF-8");
        // 设置响应内容类型为HTML，并指定字符集为UTF-8
        response.setContentType("text/html;charset=UTF-8");

        // 构建JSON需要的对象数据
        BaseResult result = new BaseResult();
        // 设置响应码为-1
        result.setCode(-1);

        // 判断异常类型并设置响应消息
        if (exception instanceof UsernameNotFoundException) {
            // 账号不存在
            result.setMessage("账号不存在");
        } else if (exception instanceof DisabledException) {
            // 账号已被禁用
            result.setMessage("账号已被禁用");
        } else if (exception instanceof LockedException) {
            // 账号已被锁定
            result.setMessage("账号已被锁定");
        } else if (exception instanceof AccountExpiredException) {
            // 账号已经过期
            result.setMessage("账号已经过期");
        } else if (exception instanceof BadCredentialsException) {
            // 密码错误
            result.setMessage("密码错误");
        } else if (exception instanceof CredentialsExpiredException) {
            // 密码已经过期
            result.setMessage("密码已经过期");
        } else {
            // 未知错误
            result.setMessage("未知错误");
        }

        // 将封装好的数据转为JSON
        // 使用ObjectMapper将BaseResult对象转换为JSON字符串，并写入响应
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }


}
